import { apiInit } from '@/services'
import {
	interfaceName,
	countByType,
	noDataText,
	myTaskLeftTab,
	myTaskRightList,
	labelIdMap,
} from '../myTaskMap'
import { ref, provide, watch, onMounted } from 'vue'
import {
	showLoadingToast,
	showConfirmDialog,
	showFailToast,
	showSuccessToast,
} from 'vant'
import { t, iTrans } from '@/entry_mobile/locales'

export default function () {
	const api = apiInit()
	const tabsCount: any = ref(0)
	const cardList: any = ref([])
	const myTaskActive = ref('myToDo')
	const myTaskConditionActive = ref('processName')
	const listCountByType: any = ref([])
	const checked: any = ref([])
	const sortChecked: any = ref('desc')
	const approvalChecked: any = ref('')
	let localTask = localStorage.getItem('subjectChecked')
	const taskOtherChecked: any = ref(
		localTask ? (localTask == 'true' ? 'showLast' : 'showAll') : 'showAll'
	)
	const typeKeyList: any = ref('')
	const conditionIsShow = ref(false)
	const approvalArr: any = ref([])
	const checkedCount: any = ref(0)
	const listFull: any = ref(false)
	const showApprovalFooter = ref(false)
	const checkedAllApproval = ref(false)
	const canCheck = ref(false)
	const refreshLoading = ref(false)
	const lazyLoading = ref(false)
	const noMore = ref(false)
	// loading中不显示无数据图片
	const STATE_CODE = ref(true)
	const searchVal = ref('')
	const myTaskPageindex = ref(1)
	const agentId = ref('')
	const agentList = ref()
	const todoTabListTotal = ref()
	const delegatedFillter = ref(
		localStorage.getItem('authority')
			? JSON.parse(localStorage.getItem('authority') || '') === false
				? 'showFilter'
				: 'unshowFilter'
			: 'showFilter'
	)
	const search = (keyword: string) => {
		searchVal.value = keyword
	}
	const addTaskInstanceId = (addTaskInstanceId: any) => {
		if (approvalArr.value?.length < 60) {
			canCheck.value = true
			!approvalArr.value.includes(addTaskInstanceId) &&
				approvalArr.value.push(addTaskInstanceId)
		} else {
			showFailToast('最多选择60条数据')
		}
	}
	const delTaskInstanceId = (delTaskInstanceId: any) => {
		canCheck.value = true
		approvalArr.value = approvalArr.value.filter((item: any) => {
			return item !== delTaskInstanceId
		})
	}
	const bathApproval = (batchApprovalValShow: any) => {
		showApprovalFooter.value = batchApprovalValShow
	}
	const reset = () => {
		checked.value = sessionStorage.getItem(`${myTaskActive.value}Checked`)
			? (sessionStorage.getItem(`${myTaskActive.value}Checked`) as any).split(
					','
			  )
			: (sessionStorage.getItem('checked') as any).split(',')
		sortChecked.value =
			sessionStorage.getItem(`${myTaskActive.value}SortChecked`) || 'desc'
		approvalChecked.value =
			sessionStorage.getItem(`${myTaskActive.value}ApprovalChecked`) || ''
		taskOtherChecked.value =
			localStorage.getItem('subjectChecked') == 'true' ? 'showLast' : 'showAll'
		typeKeyList.value =
			sessionStorage.getItem(`${myTaskActive.value}Checked`) || ''
	}
	const changeMyTaskActive = (activeVal: string) => {
		showApprovalFooter.value = false
		myTaskActive.value = activeVal
	}
	const changeRefreshLazyload = (refreshLazyload: any) => {
		;[refreshLoading.value, lazyLoading.value] = refreshLazyload
	}
	const changeChecked = (checkedList: any) => {
		checked.value = checkedList
	}
	const changeSortChecked = (sortVal: string) => {
		sortChecked.value = sortVal
	}
	const changeApprovalChecked = (approvalVal: string) => {
		approvalChecked.value = approvalVal
	}
	const changeTaskOtherChecked = (checkedVal: string) => {
		taskOtherChecked.value = checkedVal
	}
	const changeMyTaskConditionActive = (conditonActiveVal: string) => {
		myTaskConditionActive.value = conditonActiveVal
	}
	const changeTypeKeyList = (typeKeyListStr: string) => {
		typeKeyList.value = typeKeyListStr
	}
	const showCondition = (isShow: boolean) => {
		conditionIsShow.value = isShow
	}
	const changeAgentId = (val: string) => {
		agentId.value = val
	}
	const changeDelegatedFillter = (val: string) => {
		delegatedFillter.value = val
	}

	const handelApproval = async () => {
		let params = approvalArr.value.map((item: any, index: any) => {
			return { task_instance_id: item }
		})
		showConfirmDialog({
			title: t.myTask.PleaseConfirm || '请确认',
			message:
				iTrans('myTask.AgreeToApprovalTasks', { count: params?.length }) ||
				`是否同意 ${params?.length} 条审批任务？`,
			confirmButtonText: t.myTask.Confirm || '确认',
			cancelButtonText: t.myTask.Cancel || '取消',
			className: 'agree-to-approve',
			beforeClose: (action: any) => {
				return new Promise(async resolve => {
					if (action === 'confirm') {
						let { code, data } =
							await api.default.BatchApprovalTaskPrivateV2POST({
								payload: params,
							})
						if (code === '000000') {
							let successCount: any = 0
							let failCount: any = 0
							data?.forEach((item: any, index) => {
								if (item.code === '000000') {
									return ++successCount
								} else {
									return ++failCount
								}
							})
							resolve(true)
							bathApproval(false)
							init()
							// loading作为default
							if (!successCount) {
								showFailToast(`${failCount}条审批任务已失败，请重新审批`)
							} else if (!failCount) {
								showSuccessToast(
									iTrans('myTask.successTip', {
										count: successCount,
									}) || `成功处理${successCount}条审批任务`
								)
							} else {
								const text =
									iTrans('myTask.successTip', {
										count: successCount,
									}) +
									',' +
									iTrans('myTask.failTip', {
										count: failCount,
									})
								showLoadingToast(
									text !== ','
										? text
										: `成功处理${successCount}条审批任务,失败了${failCount}条`
								)
							}
						} else {
							resolve(true)
							showFailToast(t.myTask?.Error || '接口出错了')
						}
					} else {
						resolve(true)
					}
				})
			},
		})
	}
	const lazyLoad = async () => {
		let merge_task_flag = undefined
		if (myTaskActive.value === 'myToDo') {
			delegatedFillter.value === 'unshowFilter'
				? (merge_task_flag = true)
				: (merge_task_flag = false)
			localStorage.getItem('authority')
				? (merge_task_flag = JSON.parse(
						localStorage.getItem('authority') || ''
				  ))
				: ''
		} else if (myTaskActive.value === 'myTask') {
			taskOtherChecked.value == 'showAll'
				? (merge_task_flag = false)
				: (merge_task_flag = true)
		}
		let { code, data } = await api.default[interfaceName[myTaskActive.value]]({
			payload: {
				page: { page_index: ++myTaskPageindex.value, page_size: 20 },
				query: {
					subject: searchVal.value,
					status: 'approve',
					time_sort: sortChecked.value,
					type_key_list: typeKeyList.value,
					command_type: approvalChecked.value,
					merge_task_flag,
					agent_id: agentId.value,
				},
			},
		})
		if (code === '000000') {
			if (!data.rows?.length) {
				noMore.value = true
			} else {
				cardList.value = [...cardList.value, ...data.rows]
			}
		} else {
			showFailToast(t.myTask?.Error || '接口出错了')
		}
		lazyLoading.value = false
	}
	const init = async () => {
		cardList.value = []
		approvalArr.value = []
		listCountByType.value = []
		refreshLoading.value = true
		STATE_CODE.value = false
		let merge_task_flag = undefined
		if (myTaskActive.value === 'myToDo') {
			delegatedFillter.value === 'unshowFilter'
				? (merge_task_flag = true)
				: (merge_task_flag = false)
			localStorage.getItem('authority')
				? (merge_task_flag = JSON.parse(
						localStorage.getItem('authority') || ''
				  ))
				: ''
		} else if (myTaskActive.value === 'myTask') {
			taskOtherChecked.value == 'showAll'
				? (merge_task_flag = false)
				: (merge_task_flag = true)
		}
		myTaskConditionActive.value =
			myTaskActive.value === 'agentTodo'
				? 'client'
				: myTaskActive.value === 'myToDo'
				? 'processFilter'
				: 'processName'
		let taskCount, taskList, taskCountByType, taskAgentList
		;[taskCount, taskList, taskCountByType, taskAgentList] = await Promise.all([
			api.default.CountTaskPrivateV2POST({}),
			api.default[interfaceName[myTaskActive.value]]({
				payload: {
					page: { page_index: 1, page_size: 20 },
					query: {
						subject: searchVal.value,
						status: 'approve',
						time_sort: sortChecked.value,
						type_key_list: typeKeyList.value,
						command_type: approvalChecked.value,
						merge_task_flag,
						agent_id: agentId.value,
					},
				},
			}),
			api.default[countByType[myTaskActive.value]]({}),
			api.default.CountAgentTaskPrivateV2POST({
				payload: {
					page: {},
					query: {},
				},
			}),
		])
		if (taskCount.code === '000000') {
			tabsCount.value = taskCount.data
		} else {
			showFailToast(t.myTask?.Error || '接口出错了')
		}
		if (taskList.code === '000000') {
			todoTabListTotal.value = taskList.data.page.total
			cardList.value = taskList.data.rows
		} else {
			showFailToast(t.myTask?.Error || '接口出错了')
		}
		if (taskCountByType.code === '000000') {
			listCountByType.value = taskCountByType.data
			let filterArr = listCountByType.value.map((item: any) => {
				return item.process_key
			})
			sessionStorage.setItem('checked', filterArr)
			checked.value = typeKeyList.value ? checked.value : filterArr
		} else {
			showFailToast(t.myTask?.Error || '接口出错了')
		}
		if (taskAgentList.code === '000000') {
			agentList.value = taskAgentList.data
		}
		refreshLoading.value = false
		myTaskPageindex.value = 1
		noMore.value = false
		STATE_CODE.value = true
	}
	onMounted(() => {
		init()
	})
	watch([() => myTaskActive.value, () => searchVal.value], init)
	watch(
		() => approvalArr.value,
		(newVal: any) => {
			listFull.value = newVal?.length >= 60
			let curCardList = cardList.value.filter((item: any) => {
				return item.allow_batch_approval
			})
			checkedAllApproval.value =
				newVal?.length === curCardList.slice(0, 60)?.length && newVal?.length
			canCheck.value &&
				setTimeout(() => {
					canCheck.value = false
				}, 100)
		},
		{ deep: true }
	)
	return {
		tabsCount,
		init,
		refreshLoading,
		cardList,
		search,
		myTaskActive,
		searchVal,
		noDataText,
		lazyLoad,
		lazyLoading,
		noMore,
		STATE_CODE,
		listCountByType,
		checked,
		changeMyTaskActive,
		conditionIsShow,
		showCondition,
		changeTypeKeyList,
		changeChecked,
		myTaskLeftTab,
		myTaskConditionActive,
		changeMyTaskConditionActive,
		myTaskRightList,
		sortChecked,
		changeSortChecked,
		approvalChecked,
		changeApprovalChecked,
		taskOtherChecked,
		changeTaskOtherChecked,
		reset,
		changeRefreshLazyload,
		labelIdMap,
		bathApproval,
		approvalArr,
		checkedAllApproval,
		showApprovalFooter,
		addTaskInstanceId,
		checkedCount,
		delTaskInstanceId,
		canCheck,
		handelApproval,
		listFull,
		changeAgentId,
		agentList,
		delegatedFillter,
		changeDelegatedFillter,
		todoTabListTotal,
	}
}
